#!/bin/bash
# restart kubernetes container


if [[ $# < 1 ]];then
    echo; echo "Usage: $0 pod_keywords <namespace>"; echo;
    exit 1
fi

KEYWORDS=$1

NAMESPACE=${2:-__NAMESPACE}

KUBESERVER=__KUBE_MASTER

PODS=$(kubectl --server=${KUBESERVER} get pods --namespace=${NAMESPACE} | grep -i ${KEYWORDS} | cut -d' ' -f1)
PODSNUM=$(kubectl --server=${KUBESERVER} get pods --namespace=${NAMESPACE} | grep -i ${KEYWORDS} | cut -d' ' -f1 | wc -l)


PS3='Choose to restart options(input "all" for restart all and "q" to exit)> '

select pod in ${PODS};do

    if [[ "$REPLY" =~ ^[0-9]+$ ]] && [ "$REPLY" -ge 1 -a "$REPLY" -le $PODSNUM ];then
        echo -en "##########\\033[1;31m BEGIN \\033[0;39m##########";echo
            cid=$(kubectl --server=${KUBESERVER} describe pods $pod --namespace=${NAMESPACE} | grep 'Container ID:' | cut -d'/' -f3)
            nip=$(kubectl --server=${KUBESERVER} describe pods $pod --namespace=${NAMESPACE} | grep 'Node:' | cut -d'/' -f2)
            sshpass -p 'zxcasd123' ssh -o StrictHostKeyChecking=no root@$nip docker restart $cid

    elif [ "$REPLY" == 'all' ];then
        echo -en "##########\\033[1;31m BEGIN \\033[0;39m##########";echo
        for pod in ${PODS};do
            cid=$(kubectl --server=${KUBESERVER} describe pods $pod --namespace=${NAMESPACE} | grep 'Container ID:' | cut -d'/' -f3)
            nip=$(kubectl --server=${KUBESERVER} describe pods $pod --namespace=${NAMESPACE} | grep 'Node:' | cut -d'/' -f2)
            sshpass -p 'zxcasd123' ssh -o StrictHostKeyChecking=no root@$nip docker restart $cid
        done

    elif [ "$REPLY" == 'q' ];then
        break

    else
        echo -en "##########\\033[1;31m BEGIN \\033[0;39m##########";echo
        echo 'Input error'
    fi

    REPLY=''
    echo;echo -en "##########\\033[1;31m  END  \\033[0;39m##########";echo
done
